<?php

namespace StarCloud\Library;

use Framework\DiServices\HttpClient;
use Phalcon\Di;

class KuaiShouSpark
{
    private $access_token = "";
    private $appid;
    private $appsecret;
    public $cacheClass;
    /* @var $httpClient HttpClient  */
    private $httpClient;


    const AUTH_URL = "https://open.kuaishou.com/oauth2/access_token?";

    const UPLOADIMG_URL = "https://open.kuaishou.com/openapi/spark/task/uploadImg?";

    const CREATE_TASK_URL = "https://open.kuaishou.com/openapi/spark/task/create?";

    public function __construct($appId, $app_secret)
    {
        $this->appid = $appId;
        $this->appsecret = $app_secret;
        $this->cacheClass = Di::getDefault()->get('redis');
        $this->httpClient = Di::getDefault()->get('httpClient');
    }

    public function checkAuth($appid='', $appsecret='', $token='')
    {
        if (!$appid || !$appsecret) {
            $appid = $this->appid;
            $appsecret = $this->appsecret;
        }
        if ($token) { //手动指定token，优先使用
            $this->access_token=$token;
            return $this->access_token;
        }

        $authname = "sak_" . $appid;
        var_dump($authname);
        if ($rs = $this->getCache($authname)) {
            $this->access_token = $rs;
            var_dump("cache" . $this->access_token);
            return $rs;
        }

        $result = $this->http_get(self::AUTH_URL.'app_id='.$this->appid.'&app_secret='.$appsecret. '&grant_type=client_credentials');
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !isset($json['result']) || $json['result'] != 1) {
                $this->errCode = $json['result'];
                return false;
            }
            $this->access_token = $json['access_token'];
            $expire = $json['expires_in'] ? intval($json['expires_in'])-100 : 3600;
            $this->setCache($authname, $this->access_token, $expire);
            var_dump("get_access_token:" . $this->access_token);
            return $this->access_token;
        }
        return false;
    }

    public function taskCreate(
        $outerRequestId, // 外部业务id，其他接口也可用这个id进行操作，务必保证唯一性
        $title, // 任务标题（不能超过13个字)
        $promotionType = 1, // 目前仅支持3，广告分成；1, 小程序推广2. 应用下载3.广告分成4.收入分成5.线索转化
        $taskClassificationList, // 任务分类，目前列表只能填一个选项（
        $indicatorId, //任务发布类型，任务发布类型1.视频2.直播3.视频 + 直播
        $icon,
        $startTime,
        $endTime,
        $introduce, // 任务介绍，最多200字
        $statementDesc, // 结算说明，最多300字。
        $examples,// 参考视频，最少1个，最多三个
        $requirement,// 达人制作视频必须遵循的要求，不得超过300字
        $optionRequirement, // 达人制作视频必须遵循的要求，不得超过300字。
        $agreementOption = 1,
        $mpPath, // 小程序落地页地址
        $guideText, // 视频左下角引导词。
        $bindType, //达人类型 0 全部达人可见任务。2：指定达人id
        $divideRatio //广告收入分成比例0 - 99（整数）
    )
    {
        if (!$this->checkAuth()) {
            return false;
        }
        $body = [
            "outerRequestId" => $outerRequestId, // 外部业务id，其他接口也可用这个id进行操作，务必保证唯一性
            "title" => $title, // 任务标题（不能超过13个字)
            "promotionType" => $promotionType, // 目前仅支持3，广告分成；1, 小程序推广2. 应用下载3.广告分成4.收入分成5.线索转化
            "taskClassificationList" => $taskClassificationList, // 任务分类，目前列表只能填一个选项（
            "indicatorId" => $indicatorId, //任务发布类型，任务发布类型1.视频2.直播3.视频 + 直播
            "icon" => $icon,
            "startTime" => $startTime,
            "endTime" => $endTime,
            "introduce" => $introduce, // 任务介绍，最多200字
            "statementDesc" => $statementDesc, // 结算说明，最多300字。
            "examples" => $examples,// 参考视频，最少1个，最多三个
            "requirement" => $requirement,// 达人制作视频必须遵循的要求，不得超过300字
            "optionRequirement" => $optionRequirement, // 达人制作视频必须遵循的要求，不得超过300字。
            "agreementOption" => $agreementOption,
            "mpPath" => $mpPath, // 小程序落地页地址
            "guideText" => $guideText, // 视频左下角引导词。
            "bindType" => $bindType, //达人类型 0 全部达人可见任务。2：指定达人id
            "divideRatio" => $divideRatio //广告收入分成比例0 - 99（整数）
        ];

        var_dump($body);

        $response = $this->httpClient->sendPostRequest(self::CREATE_TASK_URL.'app_id='.$this->appid . '&access_token='.$this->access_token, $body, ['Content-Type' => 'application/json']);
//          $result = $this->http_post(self::CREATE_TASK_URL.'app_id='.$this->appid . '&access_token='.$this->access_token, $body);
        $result = $response->getBody()->getContents();
        var_dump($result);
        return json_decode($result, true);

        return $this->extracted($result);
    }

    public function uploadImg($data)
    {
        if (!$this->checkAuth()) {
            return false;
        }

        $result = $this->http_post(self::UPLOADIMG_URL.'app_id='.$this->appid . '&access_token='.$this->access_token, $data, [
            'Content-Type: multipart/form-data'
        ], true);
        return $this->extracted($result);
    }

    protected function setCache($cachename, $value, $expired)
    {
        //TODO: set cache implementation
        return $this->cacheClass->set($cachename, $value, $expired);
    }

    /**
     * 获取缓存，按需重载
     * @param string $cachename
     * @return mixed
     */
    protected function getCache($cachename)
    {
        return $this->cacheClass->get($cachename);
    }

    /**
     * GET 请求
     * @param string $url
     */
    private function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://")!==false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        Di::getDefault()->get('logger')->info("url is {$url} Wechat Api $sContent");
        if (intval($aStatus["http_code"])==200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function http_post($url, $param, $header = [], $post_file=false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://")!==false) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        } elseif ($post_file) {
            if ($is_curlFile) {
                foreach ($param as $key => $val) {
                    if (substr($val, 0, 1) == '@') {
                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));
                    }
                }
            }
            $strPOST = $param;
        } else {
            $aPOST = [];
            foreach ($param as $key=>$val) {
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $header);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        Di::getDefault()->get('logger')->info("url {$url} and QuaishouSpark Api $sContent");
        if (intval($aStatus["http_code"])==200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /**
     * @param bool|string $result
     * @return false|mixed
     */
    public function extracted($result)
    {
        var_dump($result);
        if ($result) {
            $json = json_decode($result, true);
            if (!$json || !isset($json['code']) || $json['code'] != 1) {
                return false;
            }
            return $json;
        }
        return false;
    }
}